
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";
import {sendCommonDict} from "@/views/loginSetup"
import {asyncRouters} from "@/routers/routers"
import {setToken, setUserInfo} from "@/utils/userData"
import { getUserId } from '@/utils/userData'
import { httpLogout } from "@http"
import {debounce} from "lodash"

// 确保 `logoutFn` 调用1次之后，1秒内会被触发。
export const handleLogout = debounce(async (fn: (res: any) => void) => {
  const userId = getUserId()
  const {code, data} = await httpLogout({userId})
  fn && fn({code, data})
}, 100, {
  'leading': true,
  'trailing': false
})

export const AppStore = defineStore('App',{
  state:() => ({
    isLoading: false,
    addRouter: [] as RouteRecordRaw[],
    commonDict: {},
    isFnPost: false
  }),
  actions: {
    toggleLoadin(isLoading: boolean = false) {
      this.isLoading = isLoading
    },
    updateAddRoute(perPageList: string[]) {
      const router = asyncRouters.filter((route: RouteRecordRaw) => {
        if(route.meta?.id){
          const pageId = route.meta.id
          if(Array.isArray(pageId)){
            return pageId.find(id => perPageList.includes(id))
          }
          return  perPageList.find(id => id === pageId)
        }
      })
      this.addRouter = router
    },
    async updateCommonDict() {
      try {
        const res = await sendCommonDict()
        this.commonDict = res.data
      } catch(error) {
        return error
      }
    },
    async userLogout(fn: (res: any) => void) {
      if(this.isFnPost){
        return
      }
      this.isFnPost = true
      handleLogout(fn)
      this.commonDict = {}
      this.addRouter = []
      setToken()
      setUserInfo()
    }
  },
})